import * as React from "react";
import { Button, Input, Modal, Row, Col, Table, message } from "antd";
import { cloneDeep } from "lodash";
import { arrRemoveItem, arrRemoveItem2 } from "../../../../../../utils/common";
import AddDeviceModal from "../AddDeviceModal";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import {
  getDevicesByFictitiousId,
  rebindBatch,
} from "../../../deviceseversapi";

export interface BindDeviceModalProps {
  visible: boolean;
  onOk: () => any;
  onCancel: () => any;
  record: any;
}

export interface BindDeviceModalState {
  visible: boolean;
  addSeleVisible: boolean; //添加可选真实设备池
  preBindingTable: any[]; //预绑定设备
  selectedRowKeys: string[];
  selectedRowRecord: any[];
  formula: string;
  record: any;
}

class BindDeviceModal extends React.Component<
  BindDeviceModalProps,
  BindDeviceModalState
> {
  state = {
    visible: false,
    addSeleVisible: false,
    selectedRowKeys: [],
    selectedRowRecord: [],
    preBindingTable: [],
    formula: "", //公式
    record: null,
  };
  private columns: columnsDataCLass[] = [
    {
      key: "variableKey",
      title: "变量",
      dataIndex: "variableKey",
      width: 100,
    },
    {
      key: "name",
      title: "设备名称",
      dataIndex: "name",
      width: 100,
    },
    {
      key: "no",
      title: "设备编号",
      dataIndex: "no",
      width: 100,
    },
  ];
  private dataSouce: any[] = [];
  onHandleOk() {
    this.props.onOk();
  }
  onHandleCancel() {
    this.props.onCancel();
    this.setState({ preBindingTable: [] });
  }
  clearState() {
    this.setState({ selectedRowKeys: [], selectedRowRecord: [] });
  }
  //选中的虚拟设备
  onSelectChange = (record, selected) => {
    let seleItem: any[] = cloneDeep(this.state.selectedRowRecord);
    let seleArr: any[] = cloneDeep(this.state.selectedRowKeys);
    if (selected) {
      //选中
      seleArr.push(record.id);
      seleItem.push(record);
    } else {
      //取消
      seleArr = arrRemoveItem(record.id, seleArr);
      seleItem = arrRemoveItem2(record.id, seleItem);
    }

    this.setState({ selectedRowKeys: seleArr, selectedRowRecord: seleItem });
  };
  //全选虚拟设备
  onSelectAll = (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
    let seleArr: any = cloneDeep(this.state.selectedRowKeys);
    let seleItem: any[] = cloneDeep(this.state.selectedRowRecord);
    if (selected) {
      changeRows.map((item) => {
        seleArr.push(item.id);
        seleItem.push(item);
        // seleArr = Array.from(new Set(seleArr));
        // seleItem = Array.from(new Set(seleItem));
        return item;
      });
    } else {
      changeRows.map((item) => {
        seleArr = arrRemoveItem(item.id, seleArr);
        seleItem = arrRemoveItem2(item.id, seleItem);
        return item;
      });
    }
    this.setState({ selectedRowKeys: seleArr, selectedRowRecord: seleItem });
  };
  remove() {
    let seleArr: any = cloneDeep(this.state.selectedRowKeys);
    // let seleItem: any[] = cloneDeep(this.state.selectedRowRecord);
    let preTable: any[] = cloneDeep(this.state.preBindingTable);
    seleArr.map((item) => {
      preTable = arrRemoveItem2(item, preTable);
      return item;
    });
    console.log(preTable);
    this.setState({
      selectedRowRecord: [],
      selectedRowKeys: [],
      preBindingTable: preTable,
    });
  }
  componentWillMount() {
    // console.log(this.props.record);
    // let str = "a0+a1+a2+a3+a4+a5+a8+a9";
    // console.log(str.match(/["a"]\d+/g));
  }
  shouldComponentUpdate(
    newProps: BindDeviceModalProps,
    newState: BindDeviceModalState
  ) {
    if (newProps.visible !== this.props.visible) {
      this.setState({ visible: newProps.visible, record: newProps.record });
      if (newProps.record) {
        this.getDataSouce(newProps.record);
        this.setState({ formula: newProps.record.formula });
      }
    }

    return true;
  }
  async getDataSouce(record: any) {
    let pream = {
      fictitiousId: record.id,
      isBind: 1,
    };
    let res: any = await getDevicesByFictitiousId(pream);
    let json: AjaxData = res;
    if (json.success) {
      let dataSouce: any[] = json.data.map((item) => {
        item.key = item.id;
        return item;
      });
      this.setState({
        preBindingTable: dataSouce,
        selectedRowRecord: dataSouce,
        selectedRowKeys: this.getRowKey(json.data),
      });
    }
  }
  getRowKey(arr) {
    let arrkey: string[] = arr.map((item: any) => {
      return item.id;
    });
    return arrkey;
  }
  //生成公式
  getFormula() {
    let { selectedRowRecord } = this.state;
    let formula: string[] = [];
    selectedRowRecord.map((item: any, i: number) => {
      formula.push(item.variableKey);
      return item;
    });
    let str: string = formula.join("+");
    this.setState({ formula: str });
  }
  //提交
  onSubmit() {
    if (this.state.formula === "" && this.state.selectedRowKeys.length > 0) {
      this.getFormula();
    }

    setTimeout(() => {
      this.checkFormula(this.state.formula);
    });
  }
  setPream() {
    let pream = {
      deviceInfo: this.getDeviceInfo(),
      fictitiousDeviceId: this.props.record.id,
      formula: this.state.formula,
    };
    this.bingDevice(pream);
  }
  checkFormula(formula: string) {
    let { selectedRowRecord } = this.state;
    let aArr = formula.match(/["a"]\d+/g);
    let bArr = selectedRowRecord.map((item: any, i: number) => {
      return item.variableKey;
    });
    let _this = this;
    //公式校验通过
    if (aArr) {
      if (this.isContained(bArr, aArr)) {
        let bLen: number = bArr.length;
        let aLen: number = aArr.length;
        if (bLen > aLen) {
          let cha = bLen - aLen;
          Modal.confirm({
            title: "您选择的设备有" + cha + "项，未纳入公式计算，是否继续?",
            onOk: () => {
              _this.setPream();
            },
            okText: "继续",
            cancelText: "再看看",
          });
        } else {
          this.setPream();
        }
      } else {
        message.error("公式校验出错，请重新生成公式");
      }
    }
  }
  isContained(aa, bb) {
    if (
      !(aa instanceof Array) ||
      !(bb instanceof Array) ||
      aa.length < bb.length
    ) {
      return false;
    }

    var aaStr = aa.toString();

    for (var i = 0; i < bb.length; i++) {
      if (aaStr.indexOf(bb[i]) < 0) return false;
    }

    return true;
  }
  getDeviceInfo() {
    let { selectedRowRecord } = this.state;
    let info: BindDeviceDto[] = [];
    selectedRowRecord.map((item: any, i: number) => {
      info.push({
        deviceId: item.id,
        variableKey: item.variableKey,
      });
      return item;
    });
    return info;
  }
  async bingDevice(pream: {
    deviceInfo: BindDeviceDto[];
    fictitiousDeviceId: string;
    formula: string;
  }) {
    let res: any = await rebindBatch(pream);
    let json: AjaxData = res;
    if (json.success) {
      message.success(json.message);
    } else {
    }
  }
  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onSelect: this.onSelectChange,
      onSelectAll: this.onSelectAll,
    };

    return (
      <>
        <Modal
          className="BindDeviceModal"
          title="绑定设备/虚拟设备名称"
          visible={this.state.visible}
          onOk={() => {
            this.onHandleOk();
          }}
          onCancel={() => {
            this.onHandleCancel();
          }}
          maskClosable={false}
        >
          <div>
            <Row>
              <Col span={4}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.getFormula();
                  }}
                >
                  生成公式
                </Button>
              </Col>
              <Col span={16} style={{ paddingRight: 10 }}>
                <Input
                  placeholder="编辑公式"
                  value={this.state.formula}
                  onChange={(e) => {
                    this.setState({ formula: e.target.value });
                  }}
                ></Input>
              </Col>
              <Col span={4}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.onSubmit();
                  }}
                >
                  保存
                </Button>
              </Col>
            </Row>
          </div>
          <div style={{ paddingTop: 10, paddingBottom: 10 }}>
            <Button
              type="primary"
              onClick={() => {
                this.setState({ addSeleVisible: true });
              }}
              style={{ marginRight: 12 }}
            >
              添加设备
            </Button>
            <Button
              type="primary"
              onClick={() => {
                this.remove();
              }}
            >
              移除设备
            </Button>
          </div>
          <Table
            columns={this.columns}
            dataSource={this.state.preBindingTable}
            rowSelection={{
              ...rowSelection,
            }}
            pagination={false}
          ></Table>
        </Modal>
        <AddDeviceModal
          visible={this.state.addSeleVisible}
          onOk={(data: any[]) => {
            let arr = data.map((item: any, index: number) => {
              item.variableKey = "a" + index;
              return item;
            });
            this.setState({
              addSeleVisible: false,
              preBindingTable: arr,
            });
          }}
          selectedRowKeys={this.state.selectedRowKeys}
          selectedRowRecord={this.state.selectedRowRecord}
          onCancel={() => {
            this.setState({ addSeleVisible: false });
          }}
        />
      </>
    );
  }
}
interface BindDeviceDto {
  deviceId: string;
  variableKey: string;
}
export default BindDeviceModal;
